<template>
    <view>
        <view v-for="(formItem, index) in formData" :key="formItem.label">
            <view v-if="formItem.type === 'upLoad'" class="flex flex-column center item-center" style="margin: 30rpx 0 0rpx" @click="() => {

              if(type === 'NoneOfThemCanBeSelected') {
                      onSelectImage();
              }
            }">
                <image
                    v-if="fileBase64"
                    style="width: 180rpx; height: 180rpx; border-radius: 50%;"
                    :src="fileBase64"
                />
                <view v-else style="width: 180rpx; height: 180rpx; border-radius: 50%; background: #ccc"/>
                <view class="text" style="margin-top: 30rpx" v-if="type==='NoneOfThemCanBeSelected'">
                    点击更换头像
                </view>
            </view>
            <view
                v-else
                class="flex between item-center"
                style="height: 100rpx; border-bottom: 1px solid #DADADA"
                @click="() => {
                    if(type === 'NoneOfThemCanBeSelected') {
                      onFormItemClick({...formItem, value: formValue[formItem.dataIndex] || ''})
                    }
                }"
                :style="{borderTop: index === 0 ? '1px solid #DADADA' : ''}"
                
            >
                <view class="text" style="font-size: 32rpx">{{formItem.name}}</view>
                <view class="text" style="font-size: 28rpx" v-if="formItem.type === 'select'">
                    {{ 
                        onGetArrObjectByProperty(mapDictCodes[formItem.mapDictCodes], formValue[formItem.dataIndex]) 
                    }}
                </view>
                <view class="text" style="font-size: 28rpx" v-else>
                    {{ 
                        formValue[formItem.dataIndex] || ''
                    }}
                </view>
            </view>
        </view>
        <view v-if="type === 'user'">
<!--            <button type="default" hover-class="hoverClass" style="color:#fff; width: 400rpx; height: 80rpx;" class="gradient-button"  @click="() => {-->
<!--                onOk(formValue);-->
<!--            }">保存个人信息</button>-->
        </view>
        <view v-else style="display: flex; flex: 1; justify-content: center; align-items: center; margin-top: 40rpx">
            <button type="default" hover-class="hoverClass" style="color:#fff; width: 400rpx; height: 80rpx;" class="gradient-button"  @click="() => {
                onOk(formValue, queryData);
            }">确定</button>
        </view>
        <!-- Input类型 -->
        <MPopup
            :title="editFormItem.name"
            :show="inputShow"
            @onClose="onClose"
        >
            <u--input
                type="text"
                v-model="inputValue"
                :placeholder="'请输入' + editFormItem.name"
                border="bottom"
            />
            <view class="flex between item-center" style="margin-top: 60rpx">
                <u-button
                    :customStyle="{width: '45%', borderRadius: '24rpx'}"
                    color="#2B5182"
                    type="primary"
                    plain
                    @click="onClose"
                >
                    取消
                </u-button>
                <u-button
                    :customStyle="{width: '45%', borderRadius: '24rpx'}"
                    color="linear-gradient(180deg, #2B5182 0%, #258FF0 100%)"
                    style="width: 48%"
                    type="primary"
                    @click="onInputConfirm"
                >
                    提交
                </u-button>
            </view>
        </MPopup>

        <!-- Select类型 -->
<!--        <u-picker-->
<!--            :show="selectShow"-->
<!--            :columns="selectData"-->
<!--            keyName="text"-->
<!--            @cancel="selectShow = false"-->
<!--            @confirm="onSelectConfirm"-->
<!--        />-->
        <MPopup
            :title="editFormItem.name"
            :show="selectShow"
            @onClose="selectShow = false"
        >
          <u-search :showAction="true" actionText="搜索"  @search="onSearch" @custom="onSearch"></u-search>
          <scroll-view scroll-y="true" style="height: 20vh; margin-top: 30rpx">
            <view>
              <view v-for="(item, index) in selectData" :key="item.value">
                <view v-if="typeof item.text === 'string' && item.text.indexOf(searchVal) !== -1" style="display: flex; flex-direction: row; align-items: center; justify-content: space-between; margin-bottom: 30rpx" @click="() => {
                  editFormItem.value = item.value
                  editFormItem.textval = item.text
                }">
                  <view>{{item.text}}</view>
                  <view style="width: 40rpx; height: 40rpx; border-radius: 50%; border: solid 1rpx #ccc;display: flex; justify-content: center; align-items: center">
                    <view v-if="item.value == editFormItem.value" style="width: 28rpx; height: 28rpx; border-radius: 50%; background: #2c405a;"></view>
                  </view>
                </view>
              </view>
            </view>
          </scroll-view>
          <view class="flex between item-center" style="margin-top: 60rpx">
            <u-button
                :customStyle="{width: '45%', borderRadius: '24rpx'}"
                color="#2B5182"
                type="primary"
                plain
                @click="selectShow = false"
            >
              取消
            </u-button>
            <u-button
                :customStyle="{width: '45%', borderRadius: '24rpx'}"
                color="linear-gradient(180deg, #2B5182 0%, #258FF0 100%)"
                style="width: 48%"
                type="primary"
                @click="onSelectConfirm"
            >
              提交
            </u-button>
          </view>
        </MPopup>
        <!-- 裁剪使用 -->
        <canvas id="myCanvas" class="canvas-case" type="2d" style="display: none" /></view>
</template>
<script>
import {
  cardIdReg,
  contraction,
  deepClone,
  getArrObjectByProperty, notificationFun, phoneReg, validCardId, validEmail,
} from "@/utils/PrjUtils";
    
    import {
        getSysPersonDetails,
        getOrganList,
        getPositionByOrganId,

    } from '@/services/user/UserInfoService';
    import {mapDictCodes} from '@/services/ServerService';
    export default {
        name: "EditUserInfo",
        props: ['type', 'userInfoList', 'onOk', 'queryData'],
        mounted() {
            this.onGetUserInfo();
            this.onMapDictCodes();
            this.formData = this.userInfoList;
        },
        data() {
            return {
                // dictCode
                mapDictCodes:{},
                fileBase64: '',
                formData: [],
                formValue: {
                    name: '',
                    eName: '',
                    cardId: '',
                    sex: {}
                },
                editFormItem: {},
                inputShow: false,
                inputValue: '',
                selectShow: false,
                selectData: [
                    [
                        {
                            text: '男',
                            value: '1'
                        },
                        {
                            text: '女',
                            value: '2'
                        }
                    ]
                ],
                searchVal:'',
            };
        },
        watch: {

        },
        methods: {
            async onMapDictCodes() {
                try {
                    let dictCode = await mapDictCodes('SsPositionKind SsPositionCategory SsPersonType ApExamineeSex SsPersonNationDict PersonEducation,StudentInvoiceType').catch(error => {
                        return {};
                    });

                    let getOrganListResult = await getOrganList(1, '').catch(error => {
                        return {};
                    });

                    let getPositionByOrganIdResult = await getPositionByOrganId().catch(error => {
                        return {};
                    });

                    this.mapDictCodes = {
                        ...dictCode,
                        getOrganList: getOrganListResult,
                        positionByOrganId: getPositionByOrganIdResult
                    }
                } catch (error) {
                    console.error('Error in onMapDictCodes:', error);
                }
            },
            onSearch(val){
              console.log(val)
              this.searchVal = val
            },
            onGetUserInfo() {
                getSysPersonDetails().then(res => {
                  let photo = ''
                      if(res.base64Header) {
                        photo=`${res.base64Header},${res.photoData}`
                      }
                    this.formValue = {...res, photoData: photo};
                    this.fileBase64=photo
                })
            },
            onFormItemClick(formItem) {
                this.editFormItem = formItem;
                this.searchVal = '';
                if(formItem.dataIndex === 'personType') {
                  return ;
                }
                if (formItem.type === 'select' || formItem.dataIndex === 'showPositionName') {
                    let arr =[];
                    if(Array.isArray(this.mapDictCodes[formItem.mapDictCodes])) {
                        for (let i = 0; i < this.mapDictCodes[formItem.mapDictCodes].length; i++) {
                          if(formItem.dataIndex === 'showPositionName') {
                            this.editFormItem.value = this.formValue.positionKind
                            arr.push({
                              text:this.mapDictCodes[formItem.mapDictCodes][i].name,
                              value:this.mapDictCodes[formItem.mapDictCodes][i].id,
                            });
                          } else {
                            arr.push({
                              text:this.mapDictCodes[formItem.mapDictCodes][i].value,
                              value:this.mapDictCodes[formItem.mapDictCodes][i].code,
                            });
                          }
                        }
                    }
                  console.log(arr, 'arr')
                    this.selectData = [...arr];
                    this.selectShow = true;
                }else if (formItem.type === 'ipt') {
                    this.inputValue = this.formValue[formItem.dataIndex] || '';
                    this.inputShow = true;
                }
            },
            onClose() {
                this.inputShow = false;
            },
            onSelectConfirm() {
              if(this.editFormItem.dataIndex === 'showPositionName') {
                this.formValue[this.editFormItem.dataIndex] = this.editFormItem.textval;
                this.formValue.positionKind = this.editFormItem.value;
                this.selectShow = false;
              } else {
                this.formValue[this.editFormItem.dataIndex] = this.editFormItem.value;
                this.selectShow = false;
              }
            },
            onInputConfirm() {
                if(this.editFormItem.dataIndex === 'phone' && this.inputValue && !phoneReg.test(this.inputValue)) {
                  return notificationFun('请输入正确的手机号');
                } else if(this.editFormItem.dataIndex === 'email' && this.inputValue && !validEmail.test(this.inputValue)) {
                  return notificationFun('请输入正确的邮箱');
                } else if(this.editFormItem.dataIndex === 'cardId' && this.inputValue && !cardIdReg.test(this.inputValue)) {
                  return notificationFun('请输入正确的身份证号');
                }
                console.log(this.editFormItem)
                console.log(this.inputValue)
                this.formValue[this.editFormItem.dataIndex] = this.inputValue;
                this.inputShow = false;
            },
            onSelectImage() {
                // 选择文件
                uni.chooseMedia({
                    count: 1, // 默认9
                    mediaType: ['image'],
                    sizeType: ['original', 'compressed'],
                    sourceType: ['album'],
                    success: (res) => {
                        const url = res.tempFiles[0].tempFilePath
                        // 获取文件管理器
                        const fileSystemManager = uni.getFileSystemManager()
                        // 读取图片信息
                        fileSystemManager.getFileInfo({
                            filePath: url,
                            success: res => {
                                // 大于4M启用压缩
                                if ((res.size / 1024 / 1024) > 4) {
                                    wx.getImageInfo({
                                        src: url,
                                        success: (cRes) => {
                                            console.log(cRes, 'res')
                                            let imgInfo = {
                                                type: cRes.type,
                                                height: cRes.height,
                                                width: cRes.width,
                                                path: cRes.path
                                            }
                                            contraction(imgInfo, 'myCanvas', this).then(newUrl => {
                                                this.fileBase64 = 'data:image/jpeg;base64,' + fileSystemManager.readFileSync(newUrl.tempFilePath, 'base64');
                                                this.formValue.photoData = 'data:image/jpeg;base64,' + fileSystemManager.readFileSync(newUrl.tempFilePath, 'base64');
                                            })
                                        },
                                        fail(err) {

                                        }
                                    })
                                } else {
                                    // 大小符合
                                    this.formValue.photoData = 'data:image/jpeg;base64,' + fileSystemManager.readFileSync(url, 'base64');
                                    this.fileBase64 = 'data:image/jpeg;base64,' + fileSystemManager.readFileSync(url, 'base64');
                                }
                            },
                        })
                    }
                })
            },
            onGetArrObjectByProperty(arr, value) {
                if(arr && value) {
                    if(getArrObjectByProperty(arr, 'code', value)?.value) {
                        return getArrObjectByProperty(arr, 'code', value)?.value
                    } else {
                        return ''
                    }
                } else {
                    return ''
                }
            },
        }
    }

</script>



<style>
page {
    background: #FFF !important;
}
.gradient-button {
    margin-top: 40rpx;
    background: -webkit-linear-gradient(#334977 , #4D83E8 );
    color: #fff;
}
.hoverClass{
    opacity: 0.5;
}
</style>
